package it.disim.tlp.webreputation.aggregatorplugin;

import java.io.File;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ManifestLoader {
	private Document doc;
	private String name;
	private String jarName;
	private String source;
	private String author;
	private String className;
	private String[] libs;
	
	public ManifestLoader(String File) throws SAXException, IOException{
		File fXmlFile = new File(File);
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder;
		try {
			dBuilder = dbFactory.newDocumentBuilder();
			doc = dBuilder.parse(fXmlFile);
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		dbFactory.setValidating(false);
		SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new File("xsd/dataAggregatorManifest.xsd"));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(fXmlFile));
	}

	public String getName() {
		if(name == null){
			Node n = doc.getElementsByTagName("name").item(0);
			name = n.getTextContent();
		}
		return name;
	}
	
	public String getJarName() {
		if(jarName == null){
			Node n = doc.getElementsByTagName("jarname").item(0);
			jarName = n.getTextContent();
		}
		return jarName;
	}

	public String getSource() {
		if(source == null){
			Node n = doc.getElementsByTagName("source").item(0);
			source = n.getTextContent();
		}
		return source;
	}

	public String getAuthor() {
		if(author == null){
			Node n = doc.getElementsByTagName("author").item(0);
			author = n.getTextContent();
		}
		return author;
	}

	public String getClassName() {
		if(className == null){
			Node n = doc.getElementsByTagName("classname").item(0);
			className = n.getTextContent();
		}
		return className;
	}

	public String[] getLibs() {
		if(libs == null){
			NodeList nl = doc.getElementsByTagName("libs");
			String[] res = new String[nl.getLength()];
			for (int i = 0; i < nl.getLength(); i++) {
				Element e = (Element) nl.item(i);
				res[i] = e.getElementsByTagName("jarname").item(0).getTextContent();
			}
			libs = res;
		}
		return libs;
	}
}
